package com.atguigu.juc.day02.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo01HelloWorld {

    // 票的库存
    private int stock = 100;

    // 锁对象
    private Lock lock = new ReentrantLock();

    // 声明一个卖票的方法
    public void saleTicket() {
        // 锁对象变成线程私有的就锁不住了
        // Lock lock = new ReentrantLock();
        try {
            // 加锁
            lock.lock();

            // 执行核心操作
            if (stock > 0) {
                System.out.println(Thread.currentThread().getName() + " 号窗口卖票一张，还剩：" + --stock + "张。");
                TimeUnit.SECONDS.sleep(1);
            }else{
                System.out.println(Thread.currentThread().getName() + " 号窗口报告：票卖完了！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 解锁
            lock.unlock();
        }

    }

    public static void main(String[] args) {

        // 1、创建当前类对象
        Demo01HelloWorld demo = new Demo01HelloWorld();

        // 2、创建三个线程代表三个卖票的窗口
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-a").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-b").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-c").start();

    }

}
